package com.amz.auth.aspect;

import com.amz.auth.annotation.RolePermission;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;

@Aspect
@Component
public class AspectAuthorize {
    @Pointcut("@annotation(com.amz.auth.annotation.RolePermission)")
    public void pointCut(){

    }

    @Before("@annotation(com.amz.auth.annotation.RolePermission)")
    public void beforeLog(JoinPoint point){
        RolePermission xeqRolePermission=null;
        try {
            xeqRolePermission = getAnnotationLog(point);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(xeqRolePermission==null){
            return;
        }

        Signature signature = point.getSignature();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        String remoteAddr = request.getRemoteAddr();//请求ip
        String[] hasAnyRole = xeqRolePermission.hasAnyRole();//log的赘述
        ArrayList<String> roles = new ArrayList<>();
        roles.add("visiter");
        for (int i = 0; i <hasAnyRole.length ; i++) {
            if(roles.contains(hasAnyRole[i])){
                //有角色，继续放行
                return;
            }
        }
        throw new RuntimeException("roles = " + hasAnyRole+"对不起，当前用户缺少访问权限");
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private RolePermission getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(RolePermission.class);
        }
        return null;
    }
}
